package com.synnex.mobile.servier.web.notification.controller.mobile;

import com.synnex.mobile.generic.core.json.JSONModel;
import com.synnex.mobile.generic.log.dao.annotation.LogClass;
import com.synnex.mobile.generic.log.dao.annotation.LogMethod;
//import com.synnex.mobile.generic.log.entity.LogEntry;
import com.synnex.mobile.generic.web.anotation.mapping.RequestMapping;
import com.synnex.mobile.generic.web.view.ModelAndView;
import com.synnex.mobile.servier.core.notification.bo.DeviceTokenBo;
import com.synnex.mobile.servier.core.notification.bo.NotificationBo;
import com.synnex.mobile.servier.core.updateTime.bo.UpdateTime;
import com.synnex.mobile.servier.core.updateTime.bo.UpdateTimeCriterion;
import com.synnex.mobile.servier.web.notification.controller.AbstractNotifyController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kerryf
 */
@RequestMapping(url = "/mobile/notification")
@LogClass(name = "mobile notification")
public class MobileNotifyController extends AbstractNotifyController {

    private static final String[] EXCLUDE_PROPERTIES = new String[]{"updateDate"};

    @RequestMapping(url = "/listNotification.do")
    @LogMethod(name = "mobile get notification list")
    public ModelAndView getNotificationList(HttpServletRequest request, HttpServletResponse response) {
        try {
            ModelAndView modelAndView = this.getNotifications(request, response);
            return modelAndView;
        } catch (Exception e) {
            return createErrorJSONModelAndView(e);
        }
    }


    @RequestMapping(url="/regToken.do")
    @LogMethod(name="register token")
    public ModelAndView regToken(HttpServletRequest request,HttpServletResponse response){
        String deviceID = request.getParameter("deviceID");
        String token = request.getParameter("token");
        try{
            DeviceTokenBo bo = new DeviceTokenBo();
            bo.setDeviceID(deviceID);
            bo.setToken(token);
            tokenService.addDeviceToken(bo);
            return createJSONModelAndView(JSONModel.create().setData(""));
        }catch (Exception e){
            return createErrorJSONModelAndView(e);
        }
    }


    public ModelAndView getNotifications(HttpServletRequest request, HttpServletResponse response) {
//        try {
        String updateTimeStr = request.getParameter("updateTime");
        String link = "http://"+this.getConfig().getFtpHost()+this.getConfig().getFtpDownLoadPath()+"/";


        JSONModel jsonModel = JSONModel.create().setExcludes(EXCLUDE_PROPERTIES);
        Map<String,Object> model = new HashMap<String,Object>();

        Long returnTime = null;
        UpdateTimeCriterion criterion = new UpdateTimeCriterion();
        criterion.setUrl(getUrl(request));

        Long updateTime = null;
        if (null != updateTimeStr && !"".equals(updateTimeStr)) {
            updateTime = Long.parseLong(updateTimeStr);
            criterion.setUpdateTime(updateTime);
        }
        UpdateTime updateTimeFromDB = updateTimeService.getUpdateTime(criterion);

        UpdateTime cache = new UpdateTime();

        if (null == updateTimeFromDB) {
            Long newTime = System.currentTimeMillis();
            cache.setUpdateTime(newTime);
            cache.setUrl(getUrl(request));
            updateTimeService.saveUpdateTime(cache);

            model = super.getNotifications(request,"mobile");
            model.remove("dataWrap");
            jsonModel.setData(model);
            jsonModel.setStatus(JSONModel.STATUS.SUCCESS);
            returnTime = newTime;
        } else {
            if (updateTime == null || updateTimeFromDB.getUpdateTime().longValue() != updateTime.longValue()) {
                returnTime = updateTimeFromDB.getUpdateTime();
                jsonModel.setStatus(JSONModel.STATUS.SUCCESS);

                model = super.getNotifications(request,"mobile");
                model.remove("dataWrap");
                jsonModel.setData(model);

            } else {
                jsonModel.setStatus(JSONModel.STATUS.CACHEED);
                returnTime = updateTimeFromDB.getUpdateTime();
            }
        }
        jsonModel.addMoreProperty("updateTime", returnTime.toString());
        jsonModel.addMoreProperty("link", link);

        return createJSONModelAndView(jsonModel);

    }

    @RequestMapping(url="/getNotify.do")
    @LogMethod(name="get notification by id")
    public ModelAndView getNotificationById(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> model = new HashMap<String,Object>();

//        LogEntry log = this.

        String link = "http://"+this.getConfig().getFtpHost()+this.getConfig().getFtpDownLoadPath()+"/";
        String id = request.getParameter("id");
        NotificationBo bo = notificationService.getNotificationBoById(Integer.parseInt(id));
        model.put("notify",bo);
        model.put("link",link);

//        LogEntry log = this.getMobileSession(request).getCurrentLogEntry(request);
//        log.setItemText(id);

        return createJSONModelAndView(model);

    }


    protected String getUrl(HttpServletRequest request) {
        String path = request.getServletPath();
        String pageNo = request.getParameter("pageNo");
        return path+"?pageNo="+pageNo;
    }
}
